package com.winai.launcher.BroadcastReceiver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jungle.mediaplayer.base.VideoInfo;
import com.ks.projectbasictools.utils.JSONUtil;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.AiMediaBean;
import com.winai.launcher.bean.AiSkillBean;
import com.winai.launcher.bean.Mp3Bean;
import com.winai.launcher.bean.db.AlarmClockBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.manager.AiMediaCurrentInfoManager;
import com.winai.launcher.manager.AiyishengManager;
import com.winai.launcher.manager.AysDeviceManager;
import com.winai.launcher.manager.VideoManager;
import com.winai.launcher.override.RandomId;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.AlarmManagerUtil;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.BlueToothUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.OpenAppUtils;
import com.winai.launcher.utils.VersionUtils;
import com.winai.launcher.view.LogicActivity;
import com.winai.launcher.view.WeatherActivity;
import com.winai.launcher.view.set.SetAboutUsActivity;
import com.winai.launcher.view.set.SetActivity;
import com.winai.launcher.view.set.SetBluetoothNewActivity;
import com.winai.launcher.view.set.SetLightActivity;
import com.winai.launcher.view.set.SetVoiceActivity;
import com.winai.launcher.view.set.SetWifiActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.utils.ThreadUtils;

/**
 * 作者：康少
 * 时间：2020/6/10 0010
 * 说明：监听思必驰语音广播
 */
@RequiresApi(api = Build.VERSION_CODES.Q)
public class SpeechReceiver extends BroadcastReceiver {
    private Context mContext;
    private static final String TAG = "---> SpeechReceiver";
    private AudioManager mAudioManager;

    public void init(Context mContext) {
        this.mContext = mContext;
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(Constant.AYS_SYSTEM);
        mFilter.addAction(Constant.SPEECH_CENTER_CONTROL);
//        mFilter.addAction(Constant.SpeechActionReminder);
        mFilter.addAction(Constant.SpeechActionSystemControl);
        mFilter.addAction(Constant.SpeechActionMediaController);
        mFilter.addAction(Constant.SpeechActionMp3Controller);
        mFilter.addAction(Constant.ACTION_AI_VERSION);
        mFilter.addAction(Constant.ACTION_OBSERVER_MESSAGE);
        mFilter.addAction(Constant.ACTION_OBSERVER_COMMAND);
        mFilter.addAction(Constant.ACTION_DIALOG_STATUS);
        mFilter.addAction(Constant.ACTION_SPEECH_COMPLETE);
        mFilter.addAction(Constant.action_aiyisheng_listening_result);
        mFilter.addAction(Constant.ACTION_CONTROL_DEVICE);
        mContext.registerReceiver(this, mFilter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "监听到思必驰语音广播，intent.getAction() = " + intent.getAction());
        if (intent.getAction() != null && intent.getAction().equals(Constant.AYS_SYSTEM)) {
            // 逻辑处理
            String data = intent.getStringExtra("data");
            Log.e(TAG, "监听到Ai语音JSON：" + data);
            executeLogic(context, data);
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.SPEECH_CENTER_CONTROL)) {
            String tgt = intent.getStringExtra("tgt");
            if (tgt != null) {
                switch (tgt) {
                    case "蓝牙状态":
                        boolean enabled = BlueToothUtils.getInstance().isEnabled();
                        notifyReceiver(context, "bluetoothState", Constant.bluetoothLinked ? "CONNECT" : enabled ? "OPEN" : "CLOSE");
                        break;
                    case "网络状态":
                        notifyReceiver(context, "networkState", "WIFI");
                        break;
                    case "当前版本":
//                        checkVersion(context);
                        notifyReceiver(context, "version", VersionUtils.getNewestVersionCode(context));
                        break;
                    case "当前播放的信息":
                        getCurrentMediaInfo(context);
                        break;
                }
            }
        }
//        else if (intent.getAction() != null && intent.getAction().equals(Constant.SpeechActionReminder)) {
//            String data = intent.getStringExtra("data");
//            Log.e(TAG, "监听到Ai-闹钟提醒JSON：" + data);
//
//            String extra = JSONUtil.getString(data, "extra", "");
//            String[] contents = JSONUtil.getStringArray(extra, "content", null);
//            ReminderBean reminderBean = new ReminderBean();
//            ReminderBean.Extra ext = new ReminderBean.Extra();
//            List<ReminderBean.Extra.ContentBean> contentBeanList = new ArrayList<>();
//            if (contents != null) {
//                for (int i = 0; i < contents.length; i++) {
//                    ReminderBean.Extra.ContentBean s = new Gson().fromJson(contents[i], new TypeToken<ReminderBean.Extra.ContentBean>() {
//                    }.getType());
//                    contentBeanList.add(s);
//                }
//            }
//            ext.setContent(contentBeanList);
//            reminderBean.setExtra(ext);
//            String intentName = JSONUtil.getString(data, "intentName", "");
//            String taskName = JSONUtil.getString(data, "taskName", "");
//            String skillId = JSONUtil.getString(data, "skillId", "");
//            String skillName = JSONUtil.getString(data, "skillName", "");
//            String object = JSONUtil.getString(data, "object", "");
//            reminderBean.setIntentName(intentName);
//            reminderBean.setTaskName(taskName);
//            reminderBean.setSkillId(skillId);
//            reminderBean.setSkillName(skillName);
//            reminderBean.setObject(object);
//            if (reminderBean.getExtra() != null && reminderBean.getExtra().getContent() != null
//                    && reminderBean.getExtra().getContent().size() > 0) {
//                for (int i = 0; i < reminderBean.getExtra().getContent().size(); i++) {
//                    int timestamp = reminderBean.getExtra().getContent().get(i).getTimestamp();
//                    String date = BaseUtils.timeStamp2Date(String.valueOf(timestamp), "yyyy/MM/dd");
//                    String time = BaseUtils.timeStamp2Date(String.valueOf(timestamp), "HH:mm:ss");
//                    String event = reminderBean.getExtra().getContent().get(i).getEvent();
//                    String repeat = reminderBean.getExtra().getContent().get(i).getRepeat();
//                    if (reminderBean.getIntentName().equals("删除提醒")
//                            || reminderBean.getIntentName().equals("sys.确认")
//                            || reminderBean.getIntentName().equals("sys.用户选择")) {
//                        removeAlarm(date, time);
//                    } else if (reminderBean.getIntentName().equals("创建提醒")) {
//                        addAlarm(context, date, time, event, formatRepeat(repeat));
//                    }
//                }
//            } else {
//                Log.e(TAG, "提醒数据异常：" + JSONUtil.formatJSONString(data != null ? data : ""));
//            }
//        }
        else if (intent.getAction() != null && intent.getAction().equals(Constant.SpeechActionMediaController)) {
            String data = intent.getStringExtra("data");
            Log.e(TAG, "监听到Ai-播放控制 JSON：" + data);
            String command = intent.getStringExtra("command");
            AiSkillBean aiSkillBean = null;
            if (!TextUtils.isEmpty(data)) {
                aiSkillBean = new Gson().fromJson(data, new TypeToken<AiSkillBean>() {
                }.getType());
            }
            if (aiSkillBean == null) {
                return;
            }

            if (isVideoPlaying(context)) {
                Log.e(TAG, "控制曲艺，data = " + data + "；command = " + command);
                if (aiSkillBean.getIntentName().equals("播放控制")) {
                    MediaControl(context, aiSkillBean.getOperate());
                } else if (aiSkillBean.getIntentName().equals("播放")) {
                    VideoManager.getInstance(context).setCommandMediaPause(false);
                    VideoManager.getInstance(context).resume();
                } else {
                    MediaControl(context, aiSkillBean.getIntentName());
                }
            } else if (isAiyishengVideoPlaying()) {
                Log.e(TAG, "控制艾益生视频，data = " + data + "；command = " + command);
                // 控制艾益生播放视频
                notifyReceiverWithAiyisheng(context, command, data);
            } else {
                Log.e(TAG, "控制QQ音乐，data = " + data + "；command = " + command);
                // 控制QQ音乐
                NotifyReceiverUtils.notifyControlQQMusic(context, command, data);
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.SpeechActionMp3Controller)) {
            String data = intent.getStringExtra("data");
            BaseUtils.longLog(TAG, "监听到Ai-音频播放 JSON：" + data);
            if (!TextUtils.isEmpty(data)) {
                resolveJSON(data);
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.SpeechActionSystemControl)) {
            String command = intent.getStringExtra("command");
            String data = intent.getStringExtra("data");
            switch (command) {
                case Constant.SystemOpenWifi:
                case Constant.SystemConnectWifi:
                    Intent intentSub = new Intent(context, SetWifiActivity.class);
                    intentSub.putExtra("titleName", "无线网络");
                    context.startActivity(intentSub);
                    break;
                case Constant.SystemOpenSettings:
                    String page = JSONUtil.getString(data, "page", "");
                    if (page.equals("屏保")) {
                        Intent setAct = new Intent(context, SetLightActivity.class);
                        setAct.putExtra("titleName", "屏幕设置");
                        context.startActivity(setAct);
                    } else {
                        Intent setAct = new Intent(context, SetActivity.class);
                        context.startActivity(setAct);
                    }
                    break;
                case Constant.SystemGoBack:
                    goBack();
                    break;
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_AI_VERSION)) {
            String aiVersion = intent.getStringExtra("aiVersion");
            LogUtils.d("获取到了AI内核版本号：" + aiVersion);
            DB_Common dbCommon = new DB_Common(mContext);
            dbCommon.add("aiVersion", aiVersion);
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_OBSERVER_MESSAGE)) {
            String message = intent.getStringExtra("message");
            String data = intent.getStringExtra("data");
            String resourceVersion = intent.getStringExtra("resourceVersion");
            AiyishengManager.getInstance(mContext).onMessageCall(message, data, resourceVersion);
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_OBSERVER_COMMAND)) {
            String command = intent.getStringExtra("command");
            String data = intent.getStringExtra("data");
            String resourceVersion = intent.getStringExtra("resourceVersion");
            AiyishengManager.getInstance(mContext).onCommandCall(command, data, resourceVersion);
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_DIALOG_STATUS)) {
            String status = intent.getStringExtra("status");
            switch (status) {
                case "start":
                    AiyishengManager.getInstance(mContext).onStartRecognition();
                    break;
                case "end":
                    AiyishengManager.getInstance(mContext).onStopRecognition();
                    break;
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_SPEECH_COMPLETE)) {
            String ttsId = intent.getStringExtra("ttsId");
            if (!TextUtils.isEmpty(ttsId)) {
                AiyishengManager.getInstance(mContext).onSpeakEnd(ttsId);
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.action_aiyisheng_listening_result)) {
            String methodName = intent.getStringExtra("methodName");
            String content = intent.getStringExtra("content");
            if (!TextUtils.isEmpty(methodName)) {
                AiyishengManager.getInstance(mContext).onListeningResult(methodName, content);
            }
        } else if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_CONTROL_DEVICE)) {
            String data = intent.getStringExtra("data");
            String command = JSONUtil.getString(data, "command", "");
            String deviceAddress = JSONUtil.getString(data, "deviceAddress", "");
            Log.e(TAG, "监听到Ai语音控制仪器JSON：" + data);
            if (!TextUtils.isEmpty(command)) {
                //发送命令到仪器
                AysDeviceManager.getInstance(mContext).sendWrite(deviceAddress, command
                        , new BleWriteCallback<BleDevice>() {
                            @Override
                            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                                ThreadUtils.ui(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastKs.show(mContext, "操作成功");
                                    }
                                });
                            }

                            @Override
                            public void onWiteFailed(BleDevice device, int failedCode) {
                                super.onWiteFailed(device, failedCode);
                                ThreadUtils.ui(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastKs.show(mContext, "操作失败:" + failedCode);
                                    }
                                });
                            }
                        });
            }
        }
    }

    @SuppressLint("LongLogTag")
    private void goBack() {
        LogUtils.e("调用goBack");
        new Thread(() -> {
            try {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(4);
            } catch (Exception e) {
                Log.e("Exception when sendKeyDownUpSync", e.toString());
            }
        }).start();
    }

    /**
     * 说明：获取当前媒体播放信息
     *
     * @param context
     */
    private void getCurrentMediaInfo(Context context) {
        AiMediaBean currentMediaInfo = AiMediaCurrentInfoManager.getInstance(context).getCurrentMediaInfo();
        if (currentMediaInfo == null) {
            LogUtils.e("获取当前播放的媒体信息为null");
            return;
        }
        Log.e(TAG, "title = " + currentMediaInfo.getTitle() + "，author = " + currentMediaInfo.getExtra().getArtist());
        sendMediaInfoReceiver(context, currentMediaInfo.getTitle(), currentMediaInfo.getExtra().getArtist());
    }

    private void MediaControl(Context context, String intentName2) {
        if (TextUtils.isEmpty(intentName2)) {
            return;
        }
        // 控制视频的音频
        switch (intentName2) {
            case "暂停播放":
            case "暂停":
                VideoManager.getInstance(context).setCommandMediaPause(true);
                VideoManager.getInstance(context).pause();
                break;
            case "停止播放":
            case "停止":
            case "退出":
                VideoManager.getInstance(context).setCommandMediaPause(true);
                VideoManager.getInstance(context).stop();
                break;
            case "重新播放":
                VideoManager.getInstance(context).replay();
                break;
            case "上一个":
                VideoManager.getInstance(context).setCommandMediaPause(false);
                VideoManager.getInstance(context).playLast();
                break;
            case "下一个":
            case "切换":
                VideoManager.getInstance(context).setCommandMediaPause(false);
                VideoManager.getInstance(context).playNext();
                break;
            case "继续":
            case "播放":
                VideoManager.getInstance(context).setCommandMediaPause(false);
                VideoManager.getInstance(context).resume();
                break;
        }
    }

    /**
     * 说明：解析JSON字符串
     */
    private void resolveJSON(String data) {
        try {
            Mp3Bean s = new Gson().fromJson(data, new TypeToken<Mp3Bean>() {
            }.getType());
            List<AiMediaBean> aiMediaBeanList = new ArrayList<>();
            List<VideoInfo> vList = new ArrayList<>();
            if (s != null && s.getContent() != null) {
                for (int i = 0; i < s.getContent().size(); i++) {
                    Mp3Bean.ContentBean contentBean = s.getContent().get(i);
                    VideoInfo videoInfo = new VideoInfo(contentBean.getLinkUrl(), i);
                    vList.add(videoInfo);
                    aiMediaBeanList.add(new AiMediaBean(contentBean.getLinkUrl()
                            , contentBean.getTitle()
                            , contentBean.getSubTitle()
                            , contentBean.getImageUrl()
                            , new AiMediaBean.ExtraBean(contentBean.getExtra().getArtist()
                            , contentBean.getExtra().getEpisode()
                            , contentBean.getExtra().getTitle()
                            , contentBean.getExtra().getResType()
                            , contentBean.getExtra().getMediaCategory())
                    ));
                }
                AiMediaCurrentInfoManager.getInstance(mContext).setMediaInfoList(aiMediaBeanList);
                VideoManager.getInstance(mContext).setVideoList(vList);
                VideoManager.getInstance(mContext).requestVideoFocus();
            } else {
                try {
                    throw new NullPointerException("思必驰音频播放列表内容为空！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 说明：是否是艾益生的视频正在播放
     */
    private boolean isAiyishengVideoPlaying() {
        return Constant.isPlayVideo;
    }

    /**
     * 说明：是否是m3u8正在播放
     */
    public boolean isVideoPlaying(Context context) {
        return VideoManager.getInstance(context).isVideoPlaying();
    }

    /**
     * 说明：QQ音乐是否打开
     */
    public boolean isRunningQQMusicWithForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param repeat "W1W2W3W4W5"
     */
    private String formatRepeat(String repeat) {
        if (!TextUtils.isEmpty((repeat))) {
            for (int i = 0; i < 8; i++) {
                repeat = repeat.replace((char) ('0' + i), "零一二三四五六日".charAt(i));
            }
            if (repeat.contains("一") && repeat.contains("二") && repeat.contains("三") && repeat.contains("四")
                    && repeat.contains("五") && repeat.contains("六") && repeat.contains("日")) {
                return "每天";
            } else if (repeat.contains("一") && repeat.contains("二") && repeat.contains("三") && repeat.contains("四")
                    && repeat.contains("五")) {
                return "工作日";
            }
            return addPoint(repeat).replace("W", "星期");
        }
        return "永不";
    }

    /**
     * @desc 添加逗号分隔符
     */
    public String addPoint(String str) {
        StringBuilder stringBuilder = new StringBuilder(str);
        int index = 2;
        int m = 0;
        int n = (str.length() - 2) / 2;
        while (m < n) {
            if (str.length() > 3) {
                stringBuilder.insert(index, "，");
                index += 2;
            }
            m++;
            index += 1;
        }
        return stringBuilder.toString();
    }

    /**
     * 说明：获取蓝牙连接状态
     */
    private void notifyReceiver(Context context, String type, String data) {
        Intent intent = new Intent();
        intent.setAction(Constant.center_control_action);
        intent.putExtra("type", type);
        intent.putExtra("data", data);
        context.sendBroadcast(intent);
    }

    /**
     * 说明：发送媒体信息
     */
    private void sendMediaInfoReceiver(Context context, String title, String author) {
        Intent intent = new Intent();
        intent.setAction(Constant.MediaCtrlCurrentInfo);
        intent.putExtra("title", title);
        intent.putExtra("author", author);
        context.sendBroadcast(intent);
    }

    /**
     * 说明：播放控制中转艾益生
     */
    private void notifyReceiverWithAiyisheng(Context context, String command, String data) {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_PLAY_CONTROL_COMMAND);
        intent.putExtra("command", command);
        intent.putExtra("data", data);
        context.sendBroadcast(intent);
    }

    private void executeLogic(Context context, String data) {
        try {
            String a = new JSONObject(data).optString("a");
            String m = new JSONObject(data).optString("m");
            if (a.equals("alarm")) {
                switch (m) {
                    case "increase"://添加指定日期时间的闹钟提醒，如：2020年5月26日早上7点16分提醒我上班
//                        createAlarm(context, data);
                        break;
                    case "open"://打开时间管理内闹钟首页
//                        Intent intent = new Intent(context, TimeManagerActivity.class);
//                        context.startActivity(intent);
//                        GlobalPublisher.Notify(GlobalPublisher.OPEN_ALARM);//打开闹钟
                        break;
                    case "off"://闹铃响起时关闭闹钟
//                        GlobalPublisher.Notify(GlobalPublisher.CLOSE_ALARM_CLOCK);//关闭闹钟
                        break;
                }
            } else if (a.equals("sound settings")) {
                switch (m) {
                    case "open"://打开声音设置首页
                        Intent intent = new Intent(context, SetVoiceActivity.class);
                        intent.putExtra("titleName", "声音设置");
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("screen settings")) {
                switch (m) {
                    case "open"://打开屏幕设置首页
                        Intent intent = new Intent(context, SetLightActivity.class);
                        intent.putExtra("titleName", "屏幕设置");
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("wifi")) {
                switch (m) {
                    case "open"://打开无线网络设置首页
                        Intent intent = new Intent(context, SetWifiActivity.class);
                        intent.putExtra("titleName", "无线网络");
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("bluetooth")) {
                switch (m) {
                    case "open"://打开蓝牙设置首页
                        Intent intent = new Intent(context, SetBluetoothNewActivity.class);
                        intent.putExtra("titleName", "蓝牙设置");
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("calendar")) {
                switch (m) {
                    case "open"://打开时间管理内日历首页
//                        Intent intent = new Intent(context, TimeManagerActivity.class);
//                        intent.putExtra("selectPage", 1);
//                        context.startActivity(intent);
//                        GlobalPublisher.Notify(GlobalPublisher.OPEN_CALENDAR);//打开日历
                        break;
                }
            } else if (a.equals("about device")) {
                switch (m) {
                    case "open"://打开关于设备首页
                        Intent intent = new Intent(context, SetAboutUsActivity.class);
                        intent.putExtra("titleName", "关于设备");
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("home page")) {
                switch (m) {
                    case "open"://打开音箱首页（有轮播的那个页面）
                        Intent intent = new Intent(context, LogicActivity.class);
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("weather")) {
                switch (m) {
                    case "open"://打开天气
                        Intent intent = new Intent(context, WeatherActivity.class);
                        context.startActivity(intent);
                        break;
                }
            } else if (a.equals("setting")) {
                switch (m) {
                    case "open"://打开设置中心
                        context.startActivity(new Intent(context, SetActivity.class));
                        break;
                }
            } else if (a.equals("machine")) {
                switch (m) {
                    case "shutdown"://音箱关机
                        Intent ii = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
                        // 是否弹出提示框
                        ii.putExtra("android.intent.extra.KEY_CONFIRM", false);
                        context.startActivity(ii);
                        break;
                    case "restart"://音箱重启
                        Intent i = new Intent("android.intent.action.REBOOT");
                        // 立即重启：1
                        i.putExtra("nowait", 1);
                        // 重启次数：1
                        i.putExtra("interval", 1);
                        // 不出现弹窗：0
                        i.putExtra("window", 0);
                        context.startActivity(i);
                        break;
                }
            } else if (a.equals("iqiyi")) {
                switch (m) {
                    case "open"://打开爱奇艺
                        OpenAppUtils.launchAPK3(mContext, "com.qiyi.video.speaker", "爱奇艺");
                        break;
                }
            } else if (a.equals("qqMusic")) {
                switch (m) {
                    case "open":
                        OpenAppUtils.launchAPK3(mContext, "com.tencent.qqmusiccar", "QQ音乐");
                        break;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 说明：创建闹钟
     */
    private void createAlarm(Context context, String data) {
        try {
            String date = new JSONObject(data).optString("date");//如：date=2020/05/26
            String time = new JSONObject(data).optString("time");//如：time=07:16
            String reminder = new JSONObject(data).optString("reminder");//如：reminder=上班
            //添加闹钟
            addAlarm(context, date, time, reminder);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void addAlarm(Context mContext, String date, String time, String reminder) {
        RandomId randomId = new RandomId();
        String id = randomId.randomId();
        AlarmClockBean mAlarmClockBean = new AlarmClockBean();
        boolean success = mAlarmClockBean.setId(id)
                .setDay(date)
                .setTime(time)
                .setWeek("永不")
                .setRemark(reminder)
                .setOpen(true)
                .save();
        if (success) {
            List<AlarmClockBean> alarmClockBeans =
                    LitePal.where("alarmId = ?", id).find(AlarmClockBean.class);
            for (AlarmClockBean bb : alarmClockBeans) {
                if (bb.isOpen()) {
                    AlarmManagerUtil.setAlarm(mContext, bb);
                } else {
                    AlarmManagerUtil.cancelAlarm(mContext, bb);
                }
            }
        }
        GlobalPublisher.Notify(GlobalPublisher.CHANGE_ALARM_CLOCK);
    }

    /**
     * @param mContext
     * @param date
     * @param time
     * @param reminder
     * @param week
     */
    private void addAlarm(Context mContext, String date, String time, String reminder, String week) {
        RandomId randomId = new RandomId();
        String id = randomId.randomId();
        AlarmClockBean mAlarmClockBean = new AlarmClockBean();
        boolean success = mAlarmClockBean.setId(id)
                .setDay(date)
                .setTime(time)
                .setWeek(week)
                .setRemark(reminder)
                .setOpen(true)
                .save();
        if (success) {
            List<AlarmClockBean> alarmClockBeans =
                    LitePal.where("alarmId = ?", id).find(AlarmClockBean.class);
            for (AlarmClockBean bb : alarmClockBeans) {
                if (bb.isOpen()) {
                    AlarmManagerUtil.setAlarm(mContext, bb);
                } else {
                    AlarmManagerUtil.cancelAlarm(mContext, bb);
                }
            }
        }
        GlobalPublisher.Notify(GlobalPublisher.CHANGE_ALARM_CLOCK);
    }

    /**
     * 说明：根据日期和时间，删除闹钟
     */
    private void removeAlarm(String date, String time) {
        List<AlarmClockBean> alarmClockBeans =
                LitePal.where("day = ? and time = ?", date, time).find(AlarmClockBean.class);
        for (AlarmClockBean bb : alarmClockBeans) {
            AlarmManagerUtil.cancelAlarm(mContext, bb);
            //删除闹钟
            LitePal.deleteAll(AlarmClockBean.class, "alarmId = ?", bb.getId());
        }
        GlobalPublisher.Notify(GlobalPublisher.CHANGE_ALARM_CLOCK);
    }
}
